/*
 * @lc app=leetcode.cn id=1592 lang=javascript
 *
 * [1592] 重新排列单词间的空格
 */

// @lc code=start
/**
 * @param {string} text
 * @return {string}
 */
var reorderSpaces = function (text) {
  const spaceLength = text.split('').filter(item => item === ' ').length;
  const words = text.trim().replace(/\s+/g, ' ').split(' ');
  if(words.length === 1) {
    return words[0] + Array(spaceLength).fill(' ').join('');
  }
  const space = Array(spaceLength / (words.length - 1) >> 0).fill(' ').join('');
  const rest = Array(spaceLength % (words.length - 1)).fill(' ').join('');
  return words.join(space) + rest;
};
// @lc code=end
